<script setup>
import { useUserStore } from '@/stores/user.js'
import { useNavbarStore } from '../../stores/navbar'
import { onMounted, ref, nextTick } from 'vue'
import http_login from '@/api/login.js'
import PostsCardDetailContainer from '@/components/PostsCardDetailContainer.vue'
import companyCardContainer from '@/components/companyCardContainer.vue'
import router from '@/router/index.js'
import http_posts from '@/api/posts.js'
import PostsCardEasyContainer from '@/components/PostsCardEasyContainer.vue'
import http_company from '@/api/company.js'
import { ElInput } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http_location from '@/api/location.js'

const userStore = useUserStore()
const navbarStore = useNavbarStore()

// 函数
// 生命周期函数
onMounted(() => {
  navbarStore.setFlag(false)
  getUserInfo()
  getConnectInfo()
})
// 获得用户信息
const getUserInfo = async () => {
  const result = await http_login.getUserInfobyId(userStore.userInfo.userId)
  if (result.code === 200) {
    userInfo.value = result.data
  }
}
// 获得用户感兴趣职位信息
const getPostsInfo = async () => {
  const result = await http_login.recordgetPosts(
    userStore.userInfo.userId,
    page.value,
    size.value
  )
  if (result.code === 200) {
    total.value = result.data.total
    UserInfoList.value = result.data.connectInfoList.userInfoList
    postsInfoList.value = result.data.connectInfoList.postsInfoList
    companyInfoList.value = result.data.connectInfoList.companyInfoList
  }
}
// 获得用户感兴趣公司信息
const getCompanyInfo = async () => {
  const result = await http_login.recordgetCompany(
    userStore.userInfo.userId,
    page.value,
    size.value
  )
  if (result.code === 200) {
    total.value = result.data.total
    companyInfoList.value = result.data.companyInfoList
    postsCountList.value = []
    bossCountList.value = []
    for (let i = 0; i < companyInfoList.value.length; i++) {
      getCount(companyInfoList.value[i].companyId)
    }
  }
}
// 获得沟通数据
const getConnectInfo = async () => {
  const result = await http_login.recordgetConnect(
    userStore.userInfo.userId,
    page.value,
    size.value
  )
  if (result.code === 200) {
    total.value = result.data.total
    UserInfoList.value = result.data.connectInfoList.userInfoList
    postsInfoList.value = result.data.connectInfoList.postsInfoList
    companyInfoList.value = result.data.connectInfoList.companyInfoList
  }
}
// 改变导航
const changeNavbar = (index) => {
  connectFlag.value = false
  companyFlag.value = false
  postsFlag.value = false
  MyPostsFlag.value = false
  MyCompanyFlag.value = false
  if (index === 0) {
    connectFlag.value = true
    getConnectInfo()
  } else if (index === 1) {
    companyFlag.value = true
    getCompanyInfo()
  } else if (index === 2) {
    postsFlag.value = true
    getPostsInfo()
  } else if (index === 3) {
    MyPostsFlag.value = true
    getMyPostsInfo()
  } else if (index === 4) {
    MyCompanyFlag.value = true
    getMyCompanyInfo()
  }
}
// 获得我发布的职位
const getMyPostsInfo = async () => {
  const result = await http_posts.getByUserIdByPage(
    userStore.userInfo.userId,
    page.value,
    size.value
  )
  if (result.code === 200) {
    total.value = result.data.total
    postsInfoList.value = result.data.records
  }
}
// 获得我创建的公司
const getMyCompanyInfo = async () => {
  const result = await http_login.getCompanyByUserId(userStore.userInfo.userId)
  if (result.code === 200) {
    total.value = 1
    myCompanyInfo.value = result.data
    postsCountList.value = []
    bossCountList.value = []
    getCount(myCompanyInfo.value.companyId)
  }
}
const getCount = async (companyId) => {
  const result = await http_company.getCount(companyId)
  if (result.code === 200) {
    postsCountList.value.push(result.data.postsCount)
    bossCountList.value.push(result.data.bossCount)
  }
}
// 修改公司
const updateCompany = async () => {
  updateCompanyVisible.value = true
  Object.assign(updateCompanyFormData.value, myCompanyInfo.value)
  if (updateCompanyFormData.value.welfare == null) {
    updateCompanyFormData.value.welfare = '[]'
  }
  updateCompanyFormData.value.welfare = JSON.parse(
    updateCompanyFormData.value.welfare
  )
  updateCompanyFormData.value.companyImage = JSON.parse(
    updateCompanyFormData.value.companyImage
  )
  const result = await http_company.getCategoryList()
  if (result.code === 200) {
    categoryList.value = result.data
  }
  fileList.value = []
  for (let i = 0; i < updateCompanyFormData.value.companyImage.length; i++) {
    fileList.value.push({
      name: updateCompanyFormData.value.companyImage[i],
      url: updateCompanyFormData.value.companyImage[i]
    })
  }
}
// 修改公司函数

const handleClose = (tag) => {
  updateCompanyFormData.value.welfare.splice(
    updateCompanyFormData.value.welfare.indexOf(tag),
    1
  )
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    updateCompanyFormData.value.welfare.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const handleAvatarSuccess = (response) => {
  console.log(response)
  if (response.code === 200) {
    updateCompanyFormData.value.companyProfilePicture = response.data
    http_company.updateProfile(myCompanyInfo.value.companyId, response.data)
  }
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 获得当前地址的图片缩略图
const setLocation = async () => {
  // 浙江省宁波市海曙区宁波工程学院翠柏校区
  if (updateCompanyFormData.value.location === '') {
    ElMessage.error('请填写正确的地址 ')
    return
  }
  const result1 = await http_location.addressToLocation(
    updateCompanyFormData.value.location
  )
  if (result1.data.status === '1') {
    if (result1.data.geocodes[0].city.endsWith('市')) {
      result1.data.geocodes[0].city = result1.data.geocodes[0].city.slice(0, -1)
    }
    updateCompanyFormData.value.city = result1.data.geocodes[0].city
    const position = result1.data.geocodes[0].location //获得经纬度
    updateCompanyFormData.value.position = position
    addressToLocation(position)
  } else {
    ElMessage.error(result1.data.info)
  }
}

// 获得高德地图提供的缩略图
const addressToLocation = (location) => {
  // 假设您已经通过Fetch API获取到了二进制数据，并将其存储在变量response中
  const key = '1384c2854dd7fad97b20b9e115717e8f' //高德地图的key
  const params = `location=${location}&size=600*240&markers=large,,我:${location}&key=${key}&zoom=16`
  var xhr = new XMLHttpRequest() // 创建XMLHttpRequest对象
  xhr.open('GET', 'https://restapi.amap.com/v3/staticmap?' + params, true) // 打开GET请求，替换为您的后端API接口地址
  xhr.responseType = 'blob' // 设置返回数据的类型为Blob对象
  xhr.onload = function () {
    if (xhr.status === 200) {
      // 请求成功
      const blob = xhr.response // 获取Blob对象
      const url = URL.createObjectURL(blob) // 创建Blob对象的URL
      imageForm.value = url
      console.log(url)
    } else {
      console.error('Request failed:', xhr.status)
    }
  }
  xhr.onerror = function () {
    console.error('Network error:', xhr.status)
  }
  xhr.send() // 发送请求
}

// 确定修改公司
const updateCompanyCommit = async () => {
  updateCompanyFormData.value.workTime =
    formatTime(time1.value[0]) + ' - ' + formatTime(time1.value[1])
  updateCompanyFormData.value.companyImage = []
  for (let i = 0; i < fileList.value.length; i++) {
    updateCompanyFormData.value.companyImage.push(fileList.value[i].url)
  }
  updateCompanyFormData.value.companyImage = JSON.stringify(
    updateCompanyFormData.value.companyImage
  )
  updateCompanyFormData.value.welfare = JSON.stringify(
    updateCompanyFormData.value.welfare
  )
  const result = await http_company.updateCompany(updateCompanyFormData.value)
  if (result.code === 200) {
    updateCompanyVisible.value = false
    ElMessage({
      message: '修改成功',
      type: 'success'
    })
    getMyCompanyInfo()
  }
}

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 日期转换
const formatTime = (inputTime) => {
  const dateObj = new Date(inputTime)
  const hours = dateObj.getHours()
  const period = hours >= 12 ? '下午' : '上午'
  const formattedTime = `${period}${dateObj.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  })}`
  return formattedTime
}

const handleCompanyImageSuccess = (response) => {
  fileList.value[fileList.value.length - 1].name = response.data
  fileList.value[fileList.value.length - 1].url = response.data
}

const handleCurrentChange = (val) => {
  page.value = val
  if (connectFlag.value) {
    getConnectInfo()
  } else if (companyFlag.value) {
    getCompanyInfo()
  } else if (postsFlag.value) {
    getPostsInfo()
  } else if (MyPostsFlag.value) {
    getMyPostsInfo()
  } else if (MyCompanyFlag.value) {
    getMyCompanyInfo()
  }
}

// 修改公司函数

// 变量
const userInfo = ref({}) // 用户信息
const total = ref(0) // 总数
const page = ref(1) // 页数
const size = ref(10) // 一页数量
const postsInfoList = ref([]) // 职位
const companyInfoList = ref([]) //公司
const UserInfoList = ref([]) //用户信息
const postsCountList = ref([])
const bossCountList = ref([])
// 修改公司变量
const myCompanyInfo = ref({}) //我创建的公司信息
const updateCompanyFormData = ref({
  companyId: '',
  name: '',
  categoryId: '',
  goPublic: '',
  numberPeople: '',
  city: '',
  location: '',
  position: '',
  description: '',
  companyProfilePicture: '',
  cipheKey: '',
  companyImage: '',
  workTime: '',
  workType: '',
  welfare: '',
  createTime: '',
  updateTime: ''
})
const categoryList = ref([]) //分类列表
const numberPeopleList = [
  '1-10人',
  '10-100人',
  '100-1000人',
  '1000-10000人',
  '10000人以上'
] //公司规模列表
const time1 = ref([new Date(2024, 0, 1, 9, 0), new Date(2024, 0, 1, 18, 0)]) //工作时间
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref(null)
const imageForm = ref('')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])
// 修改公司变量
const updateCompanyVisible = ref(false)
const postsFlag = ref(false)
const companyFlag = ref(false)
const connectFlag = ref(true)
const MyPostsFlag = ref(false)

const MyCompanyFlag = ref(false)
</script>

<template>
  <!-- 修改公司弹出框 -->
  <el-dialog v-model="updateCompanyVisible" title="修改公司信息">
    <div style="height: 400px; overflow-y: scroll">
      <el-form :model="updateCompanyFormData">
        <el-form-item label="公司名称:">
          <el-input
            style="width: 500px"
            v-model="updateCompanyFormData.name"
            placeholder="请输入公司名称"
          />
        </el-form-item>
        <el-form-item label="公司分类:">
          <el-select
            v-model="updateCompanyFormData.categoryId"
            class="m-2"
            placeholder="请选择"
            size="large"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <!-- TODO：到时候组成一下 -->
        <el-form-item label="工作时间:">
          <div class="demo-range">
            <el-time-picker
              v-model="time1"
              is-range
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </div>
        </el-form-item>
        <el-form-item label="工作类型:">
          <el-input
            style="width: 500px"
            v-model="updateCompanyFormData.workType"
            placeholder="请输入工作类型:"
          />
        </el-form-item>
        <el-form-item label="公司福利">
          <div>
            <el-tag
              v-for="item in updateCompanyFormData.welfare"
              :key="item"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="handleClose(item)"
              style="margin-right: 7px"
            >
              {{ item }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput"
            >
              + New Tag
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="是否上市:">
          <el-radio-group v-model="updateCompanyFormData.goPublic" class="ml-4">
            <el-radio :label="0" size="large">未上市</el-radio>
            <el-radio :label="1" size="large">已上市</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公司规模:">
          <el-select
            v-model="updateCompanyFormData.numberPeople"
            class="m-2"
            placeholder="请选择"
            size="large"
          >
            <el-option
              v-for="(item, index) in numberPeopleList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公司描述:">
          <div id="app">
            <quill-editor
              style="width: 600px; height: 300px"
              theme="snow"
              v-model:content="updateCompanyFormData.description"
              contentType="html"
            ></quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="公司头像:">
          <el-upload
            class="avatar-uploader"
            action="/api/v1/client/company/uploadProfile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="updateCompanyFormData.companyProfilePicture !== ''"
              :src="updateCompanyFormData.companyProfilePicture"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司相册:">
          <div style="width: 100%; color: #999">点击查看图片完整信息</div>
          <el-upload
            v-model:file-list="fileList"
            action="/api/v1/client/company/uploadCompanyImage"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleCompanyImageSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
          <!-- <el-image
            v-for="(item, index) in updateCompanyFormData.companyImage"
            :key="index"
            style="
              width: 100px;
              height: 100px;
              margin-right: 15px;
              margin-bottom: 10px;
            "
            :src="item"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="updateCompanyFormData.companyImage"
            :initial-index="index"
            fit="cover"
          /> -->
        </el-form-item>
        <el-form-item label="公司创建时间:">
          <div style="color: #999; font-size: 16px">
            {{ updateCompanyFormData.createTime }}
          </div>
        </el-form-item>
        <el-form-item label="最近修改时间:">
          <div style="color: #999; font-size: 16px">
            {{ updateCompanyFormData.updateTime }}
          </div>
        </el-form-item>
        <el-form-item label="公司用户认证密钥:">
          <el-input
            style="width: 400px"
            v-model="updateCompanyFormData.cipheKey"
            type="password"
            placeholder="公司用户认证密钥"
            show-password
          />
        </el-form-item>
        <el-form-item label="公司位置:">
          <div style="width: 100%">
            所在城市：
            <span style="color: #999; font-size: 16px">{{
              updateCompanyFormData.city
            }}</span>
          </div>
          <div style="width: 100%">
            <span>详细位置： </span>
            <el-input
              style="width: 380px"
              placeholder="请输入地址：省+市+区+目标建筑"
              v-model="updateCompanyFormData.location"
            />
            <el-button
              style="margin-left: 20px"
              type="success"
              @click="setLocation"
              >刷新定位</el-button
            >
          </div>
          <img
            style="margin-left: -40px; margin-top: 15px"
            v-if="imageForm !== ''"
            :src="imageForm"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateCompanyVisible = false">取消</el-button>
        <el-button type="primary" @click="updateCompanyCommit">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>
  <div class="box-bb">
    <div class="top"></div>
    <div class="navbar">
      <div
        style="left: 20px; top: 8px"
        @click="changeNavbar(0)"
        :class="['item', connectFlag ? 'active' : '']"
      >
        沟通过 <span v-if="connectFlag">{{ total }}</span>
      </div>
      <div
        style="left: 120px; top: 8px"
        @click="changeNavbar(1)"
        :class="['item', companyFlag ? 'active' : '']"
      >
        收藏公司 <span v-if="companyFlag">{{ total }}</span>
      </div>
      <div
        style="left: 220px; top: 8px"
        @click="changeNavbar(2)"
        :class="['item', postsFlag ? 'active' : '']"
      >
        感兴趣职位 <span v-if="postsFlag">{{ total }}</span>
      </div>
      <div
        style="left: 335px; top: 8px"
        @click="changeNavbar(3)"
        :class="['item', MyPostsFlag ? 'active' : '']"
      >
        我发布的职位 <span v-if="MyPostsFlag">{{ total }}</span>
      </div>
      <div
        style="left: 490px; top: 8px"
        @click="changeNavbar(4)"
        :class="['item', MyCompanyFlag ? 'active' : '']"
      >
        我创建的公司 <span v-if="MyCompanyFlag">{{ total }}</span>
      </div>
    </div>
    <div v-if="connectFlag" class="buttom">
      <div
        style="position: relative"
        @click="
          router.push({
            path: '/connect',
            query: { postsId: item.postsId, userId: UserInfoList[index].userId }
          })
        "
        v-for="(item, index) in postsInfoList"
        :key="item.postsId"
      >
        <div
          style="
            position: relative;
            background-color: #f7fcfb;
            z-index: 999;
            width: 100%;
            height: 35px;
            top: 15px;
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;
          "
        >
          <el-avatar
            style="margin-left: 30px; margin-top: 5px; vertical-align: middle"
            :size="25"
            :src="UserInfoList[index].avatarImage"
          />
          <span style="margin-left: 15px">{{
            UserInfoList[index].username
          }}</span>
          <span style="color: #999; margin-left: 15px">{{
            UserInfoList[index].duties
          }}</span>
        </div>
        <PostsCardDetailContainer
          style="height: 130px; width: 100%; background-color: #fff"
          :postsData="item"
          :companyData="companyInfoList[index]"
        />
      </div>
    </div>
    <div v-if="companyFlag" class="buttom">
      <div
        style="margin-bottom: 15px"
        v-for="(item, index) in companyInfoList"
        :key="index"
        @click="
          router.push({
            path: '/companyInfo',
            query: { companyId: item.companyId }
          })
        "
      >
        <!-- TODO:数据假的 -->
        <companyCardContainer :postsNumber="5" :bossNumber="6" :data="item" />
      </div>
    </div>
    <div v-if="postsFlag" class="buttom">
      <div
        @click="
          router.push({
            path: '/postsInfo',
            query: { postsId: item.postsId }
          })
        "
        v-for="(item, index) in postsInfoList"
        :key="item.postsId"
        style="position: relative"
      >
        <div
          style="
            position: relative;
            background-color: #f7fcfb;
            z-index: 999;
            width: 100%;
            height: 35px;
            top: 15px;
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;
          "
        >
          <el-avatar
            style="margin-left: 30px; margin-top: 5px; vertical-align: middle"
            :size="25"
            :src="UserInfoList[index].avatarImage"
          />
          <span style="margin-left: 15px">{{
            UserInfoList[index].username
          }}</span>
          <span style="color: #999; margin-left: 15px">{{
            UserInfoList[index].duties
          }}</span>
        </div>
        <PostsCardDetailContainer
          style="height: 130px; width: 100%; background-color: #fff"
          :postsData="item"
          :companyData="companyInfoList[index]"
        />
      </div>
    </div>
    <div v-if="MyPostsFlag" class="buttom">
      <div v-for="item in postsInfoList" :key="item.postsId">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="点击修改职位信息"
          placement="left"
        >
          <PostsCardEasyContainer :postsData="item" />
        </el-tooltip>
      </div>
    </div>
    <div v-if="MyCompanyFlag" class="buttom">
      <el-tooltip
        class="box-item"
        effect="dark"
        content="点击修改公司信息"
        placement="left"
      >
        <companyCardContainer
          :postsNumber="postsCountList[0]"
          :bossNumber="bossCountList[0]"
          :data="myCompanyInfo"
          @click="updateCompany"
        />
      </el-tooltip>
    </div>
    <div style="height: 100px">
      <el-pagination
        style="padding-left: 300px"
        background
        layout="prev, pager, next"
        :total="total"
        :page-sizes="10"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.box-bb {
  background-color: #e0f1f3;
  width: 100%;
  min-height: 87vh;
  padding-top: 20px;

  .top {
    width: 80%;
    margin: 0 auto;
    background-color: #fff;
    height: 130px;
    border-radius: 15px;
  }

  .navbar {
    width: 59%;
    margin: 15px auto;
    background-color: #fff;
    height: 42px;
    border-radius: 10px;
    display: flex;
    font-size: 16px;
    padding-left: 15px;
    position: relative;

    .item {
      position: absolute;
      height: 32px;
      cursor: pointer;
    }

    .active {
      border-bottom: 3px solid #00a6a7;

      .item {
        color: #00a6a7;
      }
    }
  }

  .buttom {
    width: 60%;
    margin: 0 auto;
    background-color: #e0f1f3;
    border-radius: 15px;
    padding-bottom: 20px;
  }
}
</style>
